﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Diagnostics;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Runtime.Remoting;
using System.Runtime.Remoting.Channels;
using System.Runtime.Remoting.Channels.Ipc;
using System.Text;
using System.Windows.Forms;
using YGame.Base;
using YGame.GameServer;

namespace AppFrame
{
	public partial class Form1 : Form
	{
		public IpcChannel ServerChannel { get; set; }

		AppFrameService MyAppFrameService;

		IGameServerProvider GameProvider;
		string CurrentPath;

		TextBoxTraceListener traceOutputor;

		public Form1()
		{
			// 初始化控件
			InitializeComponent();

		}

		protected override void OnLoad(EventArgs e)
		{
			base.OnLoad(e);

			//GameProvider = LoadMainDll(CurrentPath+"\\YGame.GameServer.dll", "YGame.Base.IGameServerProvider") as YGame.Base.IGameServerProvider;
			//if (GameProvider == null)
			//{
			//    MessageBox.Show("GameServer load fail.");
			//    txtPath.Enabled = false;
			//    btnLoad.Enabled = false;
			//}

			try
			{

				// 初始化控件内容
				CurrentPath = Path.GetDirectoryName(Application.ExecutablePath);
				txtPath.Text = CurrentPath + @"\YGame.M1.dll";

				// 初始化 TRACE
				traceOutputor = new TextBoxTraceListener(txtOutput);
				System.Diagnostics.TextWriterTraceListener txtListener = new System.Diagnostics.TextWriterTraceListener(traceOutputor);
				System.Diagnostics.Trace.Listeners.Add(txtListener);


				MyAppFrameService = new AppFrame.AppFrameService();
				MyAppFrameService.LoadModel += new LoadModelEventHandler(MyAppFrameService_LoadModel);

				Dictionary<string, string> serverArgs = AnalyseCommandLine();
				if (serverArgs.Count == 0 || serverArgs.ContainsKey("-h"))
				{
					ShowUsage();
					return;
				}
				InitIpcChannel(serverArgs);
				LoadMainModel(serverArgs);

				// 只有这个测试窗口需要这句，因为下面2个登录按钮用到
				GameProvider = YGame.Base.ServerGlobal.GameServerProvider;

			}
			catch (Exception ex)
			{
				Trace.Write(ex.Message+"\r\n"+ex.StackTrace, "Error");
				MessageBox.Show(ex.Message);
			}

		}



		private void btnLoad_Click(object sender, EventArgs e)
		{
			DllLoadHelper.LoadModelDll(txtPath.Text, null);
		}



		private void btnLogin_Click(object sender, EventArgs e)
		{
			int actorID = int.Parse(txtActorID.Text);
			

			YGame.Message.Client.AcotrLoing msg = new YGame.Message.Client.AcotrLoing();
			msg.MessageID = "YGame.GameLogic.MessageHandler.ActorLogin";
			msg.ActorID = actorID;
			string data = msg.ToJson();
			YGame.Base.ServerGlobal.GatewayConnect.OnRecieve(data);
			//GameProvider.ActorLogin(actorID);
		}

		private void btnLogout_Click(object sender, EventArgs e)
		{
			int actorID = int.Parse(txtActorID.Text);
			//GameProvider.ActorLogout(actorID);
		}




		private static void ShowUsage()
		{
			string msg = @"-md=主DLL路径
-title=窗口标题";
			MessageBox.Show(msg);
		}

		private static Dictionary<string, string> AnalyseCommandLine()
		{
			return DllLoadHelper.GetArgsDictionary(Environment.GetCommandLineArgs());
		}


		private void LoadMainModel(Dictionary<string, string> serverArg)
		{
			// 加载主游戏逻辑
			if (!serverArg.ContainsKey("-md"))
			{
				ShowUsage();
				Application.Exit();
			}
			
			string dllPath = serverArg["-md"];
			FileInfo fileInfo = new FileInfo(dllPath);
			IMainModel mainModel = DllLoadHelper.LoadMainDll(fileInfo.FullName, typeof(YGame.Base.IMainModel).FullName) as IMainModel;
			if (mainModel!=null)
			{
				mainModel.Install(MyAppFrameService);
			}
		}

		private void InitIpcChannel(Dictionary<string, string> serverArg)
		{
			ServerChannel = new IpcChannel(YGame.Base.IpcCommand.ChannelName);
			ChannelServices.RegisterChannel(ServerChannel, false);
			RemotingConfiguration.RegisterWellKnownServiceType(typeof(YGame.Base.IpcCommand), "Server", WellKnownObjectMode.Singleton);
			YGame.Base.IpcCommand.AppFrameService = MyAppFrameService;


			Trace.WriteLine(String.Format("Server IPC name:{0}", ServerChannel.ChannelName));
			Trace.WriteLine(String.Format("Server IPC priority :{0}", ServerChannel.ChannelPriority));
			foreach (var item in ServerChannel.GetUrlsForUri(YGame.Base.IpcCommand.ChannelName))
			{
				Trace.WriteLine(String.Format("Server IPC Uri :{0}", item));
			}
		}


		void MyAppFrameService_LoadModel(string path, string type)
		{
			FileInfo fileInfo = new FileInfo(path);
			IGameModel gameModel = DllLoadHelper.LoadMainDll(fileInfo.FullName, type) as IGameModel;
			if (gameModel != null)
			{
				gameModel.Install(null);
			}
		}
	}
}
